package com.aptemo.webetek.server.services;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.enums.EnumUserStatus;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.CommonService;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.data.WebetekUser;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * The server side implementation of the Invitation service.
 */
public class InvitationService
		extends HttpServlet
{
	/**
	 * 
	 */
	private static final long	serialVersionUID	= 8497010203981063987L;

	private static final String	WEBETEK_EMAIL		= "webetek.online@gmail.com";

	private UserService			userService			= UserServiceFactory.getUserService();

	private CommonService		utils				= new CommonService();

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		String url = req.getRequestURI().toString();
		String queryString = req.getQueryString();
		if (queryString != null)
		{
			url += "?" + queryString;
		}

		String id = req.getParameter("id");
		String method = req.getParameter("method");

		if (method == null || method.isEmpty() || id == null || id.isEmpty())
		{
			res.sendRedirect("/error?id=notvalidparams");
			return;
		}

		String loginUrl = userService.createLoginURL(url);
		if (!userService.isUserLoggedIn())
		{
			res.sendRedirect(loginUrl);
			return;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try
		{
			Key key = KeyFactory.stringToKey(id);
			WebetekUser user = pm.getObjectById(WebetekUser.class, key);

			Key parentKey = user.getKey().getParent();
			String teamId = KeyFactory.keyToString(parentKey);

			try
			{
				// if logged user is not the one that should be....
				WebetekUser curuser = utils.getCurrentUser(teamId);
				if (!curuser.getKey().equals(key))
				{
					res.sendRedirect(loginUrl);
					return;
				}
			}
			catch (BackendException e)
			{
				e.printStackTrace();
			}

			// check
			// if
			// (!userService.getCurrentUser().getEmail().equals(user.getEmail()))
			// {
			// //
			// out.println("<HTML><HEAD><TITLE>Weebtek user!</TITLE>" +
			// "</HEAD><BODY>Wrong user credentials! Try login as different user... <br><a href=\""
			// + userService.createLogoutURL(url) +
			// "\">logout</a></BODY></HTML>");
			// return;
			// }

			// extract method

			if (method.equals("approve"))
			{
				// set status
				user.setStatus(EnumUserStatus.ACTIVE);
			}
			else if (method.equals("reject"))
			{
				pm.deletePersistent(user);
			}

			res.sendRedirect("/#group-" + KeyFactory.keyToString(user.getKey().getParent()));
		}
		finally
		{
			out.close();
			pm.close();
		}

	}
}
